<template>
  <v-card>
    <v-toolbar class="elevation-0">
      <v-btn v-show="authorize.add" color="primary" @click="addPermission">新增权限</v-btn>
      <v-spacer/>
      <v-flex xs3>
        权限类型：
        <v-btn-toggle mandatory v-model.lazy="filter.type">
          <v-btn flat>
            全部
          </v-btn>
          <v-btn flat :value="1">
            一级菜单
          </v-btn>
          <v-btn flat :value="2">
            二级菜单
          </v-btn>
          <v-btn flat :value="3">
            其他
          </v-btn>
        </v-btn-toggle>
      </v-flex>
      <v-spacer/>
      <v-flex xs3>
        <v-text-field
          append-icon="search"
          label="搜索"
          single-line
          hide-details
          v-model="filter.search"
        />
      </v-flex>
    </v-toolbar>
    <v-divider/>
    <v-data-table
      :headers="headers"
      :items="lists"
      :pagination.sync="pagination"
      :total-items="total"
      :loading="loading"
      class="elevation-1"
      v-show="authorize.page"
    >
      <template slot="items" slot-scope="props">
        <td class="text-xs-center">{{ props.item.id }}</td>
        <td class="text-xs-center">{{ props.item.name }}</td>
        <td class="text-xs-center">{{props.item.url}}</td>
        <td class="text-xs-center">{{ props.item.method?props.item.method:"无（路由）" }}</td>
        <td class="text-xs-center">{{ formatBoolean(props.item.type) }}</td>
        <td class="text-xs-center">{{props.item.createDate}}</td>
        <td class="text-xs-center">{{ props.item.sort }}</td>
        <td class="justify-center layout px-0">
          <v-btn v-show="authorize.edit" icon @click="editPermission(props.item)">
            <i class="el-icon-edit"/>
          </v-btn>
          <v-btn v-show="authorize.delete" icon @click="deleteConfirm(props.item.id,props.item.isEnable)" v-if="props.item.isEnable">禁用</v-btn>
          <v-btn v-show="authorize.delete" icon @click="deleteConfirm(props.item.id,props.item.isEnable)" v-else>启用</v-btn>
        </td>
      </template>
    </v-data-table>

    <v-dialog v-model="show" max-width="700px" persistent scrollable>
      <v-card>
          <!--对话框的标题-->
            <v-toolbar dense dark color="primary">
            <v-toolbar-title>{{isEdit ? '修改' : '新增'}}权限</v-toolbar-title>
            <v-spacer/>
            <!--关闭窗口的按钮-->
            <v-btn icon @click="closeWindow"><v-icon>close</v-icon></v-btn>
          </v-toolbar>
          <v-card-text class="px-3" style="height: 350px">
              <v-form v-model="valid" ref="basic">
                <v-layout row>
                  <v-flex xs5>
                    <v-text-field v-model="oldPermission.name"  label="权限名称：" />
                  </v-flex>
                  <v-spacer/>
                  <v-flex xs5>
                    <v-text-field v-model="oldPermission.url"  label="权限路径：" />
                  </v-flex>
                </v-layout>
                <v-layout row>
                  <v-flex xs5>
                    <v-select
                      v-model="oldPermission.method"
                      :items="methodData"
                      label="请求方式："
                    ></v-select>
                  </v-flex>
                  <v-spacer/>
                  <v-flex xs5>
                    <v-select
                      :items="typeData"
                      item-text="text"
                      item-value="value"
                      label="权限类型"
                      v-model="oldPermission.type"
                      single-line
                    ></v-select>
                  </v-flex>
                </v-layout>
                <v-layout row>
                  <v-flex xs5>
                    <v-cascader
                      url="/user/author/permission/list"
                      showAllLevels
                      changeSelect
                      v-model="oldPermission.parentId"
                      ref="cascader"
                      label="请选择上级权限"/>
                  </v-flex>
                  <v-spacer/>
                  <v-flex xs5>
                    <v-text-field v-model="oldPermission.sort"  label="序号(只对菜单有效)：" />
                  </v-flex>
                </v-layout>
                <v-layout row>
                  <v-flex xs5>
                    <v-text-field v-model="oldPermission.icon"  label="图标(只对菜单有效)：" />
                  </v-flex>
                  <v-spacer/>
                </v-layout>
               </v-form>
          </v-card-text>
          <v-card-actions>
              <v-spacer/>
              <v-btn color="blue darken-1" flat @click.native="show=false">取消</v-btn>
              <v-btn color="blue darken-1" flat @click.native="save">保存</v-btn>
          </v-card-actions>
      </v-card>
   </v-dialog>
  </v-card>
</template>

<script>

  export default {
    name: "permission",
    data() {
      return {
        filter: {
          type: 1, // 权限类型
          search: '', // 搜索过滤字段
        },
        total: 0, // 总条数
        lists: [], // 当前页品牌数据
        loading: true, // 是否在加载中
        pagination: {}, // 分页信息
        headers: [
          {text: 'id', align: 'center', sortable: false, value: 'id'},
          {text: '权限名', align: 'center', sortable: false, value: 'name'},
          {text: '路径', align: 'center', sortable: false, value: 'url'},
          {text: '请求方式', align: 'center', value: 'method', sortable: false},
          {text: '权限类型', align: 'center', value: 'type', sortable: false},
          {text: '创建时间', align: 'center', value: 'createDate', sortable: false},
          {text: '排序', align: 'center', value: 'sort', sortable: false},
          {text: '操作', align: 'center', sortable: false}
        ],
        show: false,// 控制对话框的显示
        isEdit: false, // 是否是编辑
        methodData:['GET','POST','PUT','DELETE'],
        typeData: [
                  { value: 1, text: '一级菜单' },
                  { value: 2, text: '二级菜单' },
                  { value: 3, text: '其他' }
                ],
        valid:false,
        oldPermission:{},
        authorize:{page:false,add:false,edit:false,delete:false}
      }
    },
    mounted() { // 渲染后执行
      // 查询数据
      this.getDataFromServer();
    },
    created(){
      this.$http({
        method: 'GET',
        url: '/user/author/query/other/auth?url='+this.$route.path,
        headers: {"x-authorize-token":this.$storeGet("L_TOKEN")},
      }).then((resp) => {
        if(resp.data.code == 1){
          resp.data.data.forEach(m => {
            if(m.url == '/user/author/permission/page' && m.method == "POST"){
                this.authorize.page=true;
            }
            if(m.url == "/user/author/permission" && m.method == "POST"){
              this.authorize.add=true;
            }
            if(m.url == "/user/author/permission" && m.method == "PUT"){
              this.authorize.edit=true;
            }
            if(m.url == "/user/author/permission" && m.method == "DELETE"){
              this.authorize.delete=true;
            }
          })
        }else{
          this.$message.error(resp.data.message);
        }
      }).catch(() => {
        this.$message.error("服务器异常");
      });
    },
    watch: {
      pagination: { // 监视pagination属性的变化
        deep: true, // deep为true，会监视pagination的属性及属性中的对象属性变化
        handler() {
          // 变化后的回调函数，这里我们再次调用getDataFromServer即可
          this.getDataFromServer();
        }
      },
      filter: {// 监视搜索字段
        deep: true,
        handler() {
          this.getDataFromServer();
        }
      }
    },
    methods: {
      getDataFromServer() { // 从服务的加载数的方法。
        // 发起请求
        this.$http({
          method: 'post',
          url: '/user/author/permission/page',
          headers: {"x-authorize-token":this.$storeGet("L_TOKEN")},
          data:{
            key: this.filter.search, // 搜索条件
            type: this.filter.type == 0?null:this.filter.type,
            page: this.pagination.page,// 当前页
            rows: this.pagination.rowsPerPage// 每页大小
          }
        }).then( resp => {
          if(resp.data.code == 1){
            this.lists = resp.data.data.items;
            this.total = resp.data.data.total;
            // 完成赋值后，把加载状态赋值为false
            this.loading = false;
          }else{
            this.$message.error(resp.data.message);
          }
        }).catch(() => {
          this.$message.error("服务器异常");
        });
      },
      addPermission() {
        this.isEdit = false;
        this.show = true;
        // 重置表单
        this.$refs.basic.reset();
        // 需要手动清上级权限
        this.oldPermission.parentId = null;
        this.oldPermission.id=null;

      },
      editPermission(obj){
        this.isEdit = true;
        this.show = true;
        this.oldPermission={
          id:obj.id,
          name:obj.name,
          url:obj.url,
          method:obj.method,
          sort:obj.sort,
          icon:obj.icon,
          id:obj.id,
          type:obj.type,
          parentId:null
        };
        if(obj.parentId != 0){
          this.$http.get("/user/author/permission/get/"+obj.parentId,{headers: {"x-authorize-token":this.$storeGet("L_TOKEN")}}).then( resp => {
            if(resp.data.code == 1){
              this.oldPermission.parentId=[{id:resp.data.data.id,name:resp.data.data.name}];
            }else{
              this.$message.error(resp.data.message);
            }
          }).catch(() => {
            this.$message.error("服务器异常");
          });
        }
      },
      save(){
        if(this.oldPermission.parentId != null){
          let parentId = this.oldPermission.parentId[this.oldPermission.parentId.length-1];
          this.oldPermission.parentId=parentId.id;
        }else{
          this.oldPermission.parentId=0;
        }
        this.$http({
            method: this.isEdit ? 'put' : 'post',
            url: '/user/author/permission',
            data: this.oldPermission,
            headers: {"x-authorize-token":this.$storeGet("L_TOKEN")}
        }).then((resp) => {
            if(resp.data.code == 1){
              // 关闭窗口
              this.show = false;
              this.$message.success("保存成功！");
              //跟新上级权限
              this.$refs.cascader.updatePermission();
              this.getDataFromServer();
            }else{
              this.$message.error(resp.data.message);
            }
        }).catch(() => {
          this.$message.error("服务器异常");
        });
      },
      deleteConfirm(id,isEnable){
        this.$message.confirm('权限操作请小心，是否继续?', '提示', {
          confirmButtonText: '确定删除',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.deletePermission(id,isEnable);
        }).catch(()=>{
          this.$message.info('已取消删除');
        })
      },
      deletePermission(id,isEnable){
        this.$http({
            method: 'delete',
            url: '/user/author/permission',
            data: {id:id,isEnable:isEnable},
            headers: {"x-authorize-token":this.$storeGet("L_TOKEN")}
        }).then((resp) => {
            if(resp.data.code == 1){
              this.$message.success(isEnable?"禁用成功":"启用成功");
              this.getDataFromServer();
            }else{
              this.$message.error(resp.data.message);
            }
        }).catch(() => {
          this.$message.error("服务器异常");
        });
      },
      closeWindow(){
        // 关闭窗口
        this.show = false;
      },
      formatBoolean(type){
        if(type == 1){
          return "一级菜单";
        }else if(type == 2){
          return "二级菜单";
        }else{
          return "其他";
        }
      }
    }
  }
</script>

<style scoped>

</style>
